from typing import Any
from mcp.server.fastmcp import FastMCP
import asyncio

# 初始化 MCP 服务器
mcp = FastMCP("CounterServer")

counter = 0

@mcp.tool()
async def increment_counter(value: int) -> int:
    """给计数值增加 value 值，并返回新的计数值."""
    global counter
    counter += value
    return counter

@mcp.tool()
async def get_counter() -> int:
    """返回当前的计数值."""
    global counter
    return counter

async def auto_increment():
    """每 5 秒自动增加计数器值."""
    while True:
        await asyncio.sleep(5)
        await increment_counter(1)
        print(f"Counter increased to: {counter}")

async def main():
    """启动 MCP 服务器和自动增加任务."""
    # 创建自动增加任务
    auto_increment_task = asyncio.create_task(auto_increment())
    
    try:
        # 启动 MCP 服务器
        await mcp.run(transport='stdio')
    finally:
        # 如果 MCP 服务器结束，取消自动增加任务
        auto_increment_task.cancel()
        try:
            await auto_increment_task
        except asyncio.CancelledError:
            pass

if __name__ == "__main__":
    asyncio.run(main())
